package com.coldchain.common.resource;


import com.coldchain.common.vo.MenuVo;
import com.coldchain.common.resource.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @ClassName A
 * @Description TODO
 * @Author fangliai
 * @Date 2018/9/7 18:06
 * @Vesion 1
**/
@Configuration
public class ResourceLoadListener implements ApplicationListener<ContextRefreshedEvent> {
    private volatile AtomicBoolean isInit=new AtomicBoolean(false);

    private Logger log= LoggerFactory.getLogger(ResourceLoadListener.class);
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //防止重复触发
        if(!isInit.compareAndSet(false,true)) {
            return;
        }
      log.info("正在配制系统资源<<<<<<<<<<<<");
      Map<String,Object> annotations=event.getApplicationContext().getBeansWithAnnotation(Resource.class);

      annotations.forEach((v,k)->{
          log.info(v);
          Resource rootResource=  k.getClass().getAnnotation(Resource.class);
          RequestMapping rootMapping=k.getClass().getAnnotation(RequestMapping.class);
          Arrays.stream(k.getClass().getMethods()).forEach(m ->{
               Resource mResource=m.getAnnotation(Resource.class);
              if(mResource!=null){
                  log.info(mResource.menuName());

                  RequestMapping mapping=m.getAnnotation(RequestMapping.class);
                  String url=rootMapping.name()+mapping.name();
                  if(mResource.isMenu()){
                      ResourceManage.addMenu(new MenuVo(mResource.menuName(),url, StringUtils.isEmpty(mResource.groupName())?rootResource.groupName():mResource.groupName()));
                  }
              }
            });
      });
    }


}
